<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Admin Dashboard</title>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: Arial, sans-serif;
        background-color: #f5f5f5;
      }

      .header {
        background-color: #333;
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        margin-bottom: 20px;
        font-size: 16px;
        height: 100px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        box-sizing: border-box;
      }

      .header h1 {
        font-size: 24px;
        margin: 0;
      }

      .header p {
        margin: 5px 0 0 0;
        font-size: 14px;
        opacity: 0.9;
      }

      .user-info {
        font-size: 14px;
        margin-top: 10px;
        opacity: 0.9;
      }

      .dashboard {
        display: grid;
        grid-template-columns: 1fr;
        gap: 20px;
      }

      .stats {
        display: flex;
        justify-content: flex-start;
        gap: 20px;
        margin-bottom: 20px;
        background-color: white;
        padding: 15px;
        border-radius: 5px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .stat-card {
        background-color: #f8f9fa;
        padding: 10px 15px;
        border-radius: 5px;
        text-align: center;
        min-width: 120px;
      }

      .stat-number {
        font-size: 1.5em;
        font-weight: bold;
        color: #007bff;
      }

      .main-content {
        background-color: white;
        padding: 20px;
        border-radius: 5px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .log-container {
        margin-top: 20px;
        background-color: white;
        border-radius: 5px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .log-header {
        padding: 10px 15px;
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .log-title {
        margin: 0;
        font-size: 16px;
      }

      .log-toggle {
        background: none;
        border: none;
        font-size: 16px;
        cursor: pointer;
      }

      .log-area {
        background-color: #333;
        color: #00ff00;
        padding: 15px;
        border-radius: 0 0 5px 5px;
        height: 200px;
        overflow-y: auto;
        font-family: monospace;
        display: none;
      }

      .log-area.expanded {
        display: block;
      }

      .client-section {
        margin-bottom: 20px;
      }

      .section-title {
        margin-top: 0;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
      }

      .client-list {
        list-style: none;
        padding: 0;
      }

      .client-item {
        padding: 15px;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
      }

      .client-info {
        flex-grow: 1;
        margin-right: 15px;
      }

      .client-info small {
        display: block;
        margin-top: 5px;
        color: #666;
      }

      .client-info pre {
        white-space: pre-wrap;
        word-wrap: break-word;
        background-color: #f8f9fa;
        padding: 5px;
        border-radius: 3px;
        max-width: 500px;
        overflow-x: auto;
      }

      .client-item:last-child {
        border-bottom: none;
      }

      .disconnect-btn {
        background-color: #dc3545;
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 3px;
        cursor: pointer;
      }

      .disconnect-btn:hover {
        background-color: #c82333;
      }

      .status-indicator {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        margin-right: 10px;
      }

      .status-connected {
        background-color: #28a745;
      }

      .status-disconnected {
        background-color: #dc3545;
      }

      .refresh-btn {
        background-color: #007bff;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
      }

      .refresh-btn:hover {
        background-color: #0069d9;
      }

      .log-area {
        background-color: #333;
        color: #00ff00;
        padding: 15px;
        border-radius: 5px;
        height: 200px;
        overflow-y: auto;
        font-family: monospace;
        margin-top: 20px;
      }

      .stats {
        display: flex;
        justify-content: space-around;
        margin-bottom: 20px;
      }

      .stat-card {
        background-color: white;
        padding: 15px;
        border-radius: 5px;
        text-align: center;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        flex: 1;
        margin: 0 10px;
      }

      .stat-number {
        font-size: 2em;
        font-weight: bold;
        color: #007bff;
      }
    </style>
  </head>
  <body>
    <div class="header">
      <h1>WebSocket Server Admin Dashboard</h1>
      <p>管理服务器连接和客户端</p>
      <div class="user-info">
        当前用户名: <span id="currentUsername">加载中...</span> <br />
        当前用户ID:
        <span id="currentUserId">加载中...</span>
      </div>
    </div>

    <div class="stats">
      <div class="stat-card">
        <div class="stat-number" id="clientCount">0</div>
        <div>在线客户端</div>
      </div>
      <div class="stat-card">
        <div class="stat-number" id="serverStatus">-</div>
        <div>服务器状态</div>
      </div>
    </div>

    <div class="dashboard">
      <div class="main-content">
        <div class="client-section">
          <h2 class="section-title">在线客户端</h2>
          <button class="refresh-btn" id="refreshBtn">刷新客户端列表</button>
          <ul class="client-list" id="clientList">
            <li>暂无客户端连接</li>
          </ul>
        </div>

        <div class="log-container">
          <div class="log-header" id="logHeader">
            <h3 class="log-title">系统日志</h3>
            <button class="log-toggle" id="logToggle">﹀</button>
          </div>
          <div class="log-area" id="logArea">
            <div>系统日志将显示在这里...</div>
          </div>
        </div>
      </div>
    </div>

    <script type="module">
      import { createUser } from "/packages/user/main.js";

      // 创建管理员用户
      const user = await createUser({ user: "test-admin1" });

      // 显示当前用户名
      const currentUsernameElement = document.getElementById("currentUsername");
      const currentUserIdElement = document.getElementById("currentUserId");

      const info = await user.info();
      currentUsernameElement.textContent = info.name;
      currentUserIdElement.textContent = user.userId;

      const serverUrl = "ws://localhost:18290";

      // 连接到服务器（管理员模式）
      const serverClient = await user.connectServer(serverUrl, {
        admin: 1,
        password: "admin123",
      });

      // 更新日志区域
      function updateLog(message) {
        const logArea = document.getElementById("logArea");
        const time = new Date().toLocaleTimeString();
        logArea.innerHTML += `<div>[${time}] ${message}</div>`;
        logArea.scrollTop = logArea.scrollHeight;
      }

      // 更新客户端列表
      function updateClientList(clients) {
        const clientList = document.getElementById("clientList");
        const clientCount = document.getElementById("clientCount");

        clientCount.textContent = clients.length;

        if (clients.length === 0) {
          clientList.innerHTML = "<li>暂无客户端连接</li>";
          return;
        }

        clientList.innerHTML = "";

        clients.forEach((client) => {
          const li = document.createElement("li");
          li.className = "client-item";

          const connectTime = new Date(client.connectTime).toLocaleString();

          // 格式化用户信息
          let userInfo = "";
          if (client.userInfo) {
            try {
              userInfo =
                typeof client.userInfo === "string"
                  ? client.userInfo
                  : JSON.stringify(client.userInfo, null, 2);
            } catch (e) {
              userInfo = "[无法解析的用户信息]";
            }
          }

          li.innerHTML = `
            <div class="client-info">
              <span class="status-indicator status-connected"></span>
              <strong>ID:</strong> ${client.id}<br>
              <strong>用户名:</strong> ${client.username || "N/A"}<br>
              <strong>用户ID:</strong> ${client.userId || "N/A"}<br>
              <strong>状态:</strong> ${client.state || "N/A"}<br>
              <strong>延迟:</strong> ${client.delay}ms<br>
              <small>连接时间: ${connectTime}</small><br>
              <!-- <small>用户信息: <pre>${userInfo || "N/A"}</pre></small> -->
            </div>
            <button class="disconnect-btn" data-client-id="${
              client.id
            }">断开</button>
          `;

          clientList.appendChild(li);
        });

        // 为断开按钮添加事件监听器
        document.querySelectorAll(".disconnect-btn").forEach((button) => {
          button.addEventListener("click", async (e) => {
            const clientId = e.target.getAttribute("data-client-id");
            try {
              await serverClient.disconnectClient(clientId);
              updateLog(`已发送断开客户端 ${clientId} 的连接请求`);
              // 延迟刷新列表以显示断开结果
              setTimeout(async () => {
                try {
                  const clients = await serverClient.getClients();
                  updateClientList(clients);
                } catch (error) {
                  updateLog(`刷新客户端列表失败: ${error.message}`);
                }
              }, 1000);
            } catch (error) {
              updateLog(`断开客户端 ${clientId} 失败: ${error.message}`);
            }
          });
        });
      }

      // 监听服务器消息
      serverClient.addEventListener("message", (event) => {
        const { type } = event.detail;

        if (type === "connections_info") {
          const { clients } = event.detail;
          updateLog(`获取到 ${clients.length} 个客户端连接信息`);
          updateClientList(clients);
        } else if (type === "success") {
          updateLog(`操作成功: ${event.detail.message}`);
        } else if (type === "error") {
          updateLog(`错误: ${event.detail.message}`);
        } else {
          updateLog(`收到消息: ${type}`);
        }
      });

      // 刷新按钮事件
      document
        .getElementById("refreshBtn")
        .addEventListener("click", async () => {
          try {
            const clients = await serverClient.getClients();
            updateLog("正在刷新客户端列表...");
            updateClientList(clients);
          } catch (error) {
            updateLog(`刷新客户端列表失败: ${error.message}`);
          }
        });

      // 页面加载完成后自动刷新一次
      setTimeout(async () => {
        try {
          const clients = await serverClient.getClients();
          updateLog("初始化客户端列表...");
          updateClientList(clients);
        } catch (error) {
          updateLog(`初始化客户端列表失败: ${error.message}`);
        }

        // 更新服务器状态
        const serverStatus = document.getElementById("serverStatus");
        if (
          serverClient.socket &&
          serverClient.socket.readyState === WebSocket.OPEN
        ) {
          serverStatus.textContent = "运行中";
          serverStatus.style.color = "#28a745";
        } else {
          serverStatus.textContent = "离线";
          serverStatus.style.color = "#dc3545";
        }
      }, 300);

      // 监听连接状态变化
      serverClient.addEventListener("authed", () => {
        updateLog("管理员已认证");
      });

      serverClient.addEventListener("close", () => {
        updateLog("与服务器的连接已断开");
        const serverStatus = document.getElementById("serverStatus");
        serverStatus.textContent = "离线";
        serverStatus.style.color = "#dc3545";
      });

      // 日志区域折叠功能
      const logHeader = document.getElementById("logHeader");
      const logArea = document.getElementById("logArea");
      const logToggle = document.getElementById("logToggle");

      logHeader.addEventListener("click", () => {
        logArea.classList.toggle("expanded");
        logToggle.textContent = logArea.classList.contains("expanded")
          ? "︿"
          : "﹀";
      });
    </script>
  </body>
</html>
